#!/bin/sh /etc/rc.common
#
# Copyright (C) 2023 sirpdboy herboy2008@gmail.com
#

START=99
USE_PROCD=1

NAME=timecontrol
LOCK="/var/lock/$NAME.lock"
CR=/etc/crontabs/root

start_instance() {
	 procd_open_instance
	 procd_set_param command /usr/bin/timecontrolctrl
	 procd_set_param respawn
	 procd_set_param stderr 1
	 procd_close_instance
}

_timecontrol_start() {
	 if [ "$(grep -c 'option enable .1.' /etc/config/$NAME 2>/dev/null)" -gt "0" ]; then

	    touch $LOCK
	    timecontrol start
	    start_instance
	    (crontab -l ; echo "00 1 * * * /etc/init.d/timecontrol start") | sort - | uniq - | crontab -
	 fi
}

start_service(){
	[ -f $LOCK ] && exit
	stop_service
	_timecontrol_start
	rm -f $LOCK
}

service_triggers() {
 	 procd_add_reload_trigger 'timecontrol'
}

stop_service(){
	kill -9 $(busybox ps -w | grep 'timecontrolctrl' | grep -v 'grep' | awk '{print $1}') >/dev/null 2>&1
	sed -i '/timecontrol/d' $CR >/dev/null 2>&1
	rm -f $LOCK 2>/dev/null
	timecontrol stop
}

